package servlet.download;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang3.StringUtils;

import Jsonutil.JsonDateValueProcessor;
import dao.SoftDao;
import entity.Software;

public class DownloadServlet extends HttpServlet {

	public DownloadServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); 
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String softName = request.getParameter("softName");
		String secret = request.getParameter("secret");
		if(!StringUtils.isEmpty(softName)) {
			softName = URLDecoder.decode(URLDecoder.decode(softName, "UTF-8"), "UTF-8");
		}
		if(!StringUtils.isEmpty(secret)) {
			secret = URLDecoder.decode(URLDecoder.decode(secret, "UTF-8"), "UTF-8");
		}
		SoftDao softDao = new SoftDao();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		JSONObject jsonObject = new JSONObject();
		List<Software> list = softDao.querySofts(softName, secret);
		if(list != null && list.size() > 0) {
			JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
			jsonObject.put("retCode", "1");
			jsonObject.put("softs", jsonArray);
		} else {
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "没有记录");
		}
		
		out.print(jsonObject.toString());
		out.close();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	public void init() throws ServletException {
	}

}
